package com.redis.Web;

import com.redis.Service.ShopBiz;
import com.redis.Service.UserBiz;
import com.redis.Util.countUtils;
import com.redis.po.UserPo;
import com.redis.vo.ShopEntity;
import com.redis.vo.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.Set;

@Controller
@RequestMapping("/jsp")
public class UserWeb<pulic> {
    @Resource
    private UserBiz userBiz;
    @Resource
    private ShopBiz shopBiz;

    Jedis jedis = new Jedis("192.168.36.129", 6379);
    final int limit = 3;
    //登陆
    @PostMapping("/golog")
    public String logUser(HttpServletRequest request, HttpSession session) {
        jedis.auth("123456");
        System.out.println(jedis.ping());
        String username = null;
        String password = null;
        UserPo userPo = new UserPo();
        if (request.getParameter("username") != null) {
            username = request.getParameter("username");
        }
        if (request.getParameter("password") != null) {
            password = request.getParameter("password");
        }
        userPo.setUsername(username);
        userPo.setPassword(password);
        //查询登陆
        UserEntity user = userBiz.loginUser(userPo);
        int count = 0;
        String key = username;
        if (jedis.exists(key)) {
            System.out.println(jedis.get(key));
            count = Integer.parseInt(jedis.get(key));
        } else {
            jedis.set(key, String.valueOf(count));
        }
        if (user != null) {
            //登陆成功
            //并且要count<3
            if (count < limit) {
                //将用户的信息存入session
                request.getSession().setAttribute("userid", user.getUserid());
                request.getSession().setAttribute("username", user.getUsername());
                request.getSession().setAttribute("password", user.getPassword());
                // 删除key
                jedis.del(key);
                //登陆成功就增加一次首页浏览量
                String key1 = "pageview";
                if (jedis.exists(key1)) {
                    System.out.println(jedis.get(key1));
                    jedis.incrBy(key1, 1);
                } else {
                    jedis.set(key1, String.valueOf(1));
                }
                int count1 = Integer.parseInt(jedis.get(key1));
                request.getSession().setAttribute("pageviews", count1);
                //---------显示销售排行前2的---------
                String shopList = "shopList";
                //排序
                Set<String> list = jedis.zrevrange(shopList, 0, 1);
                Iterator<String> iterator =list.iterator();
                int i=1;
                String name="";
                while(iterator.hasNext()&&i<=3){
                    //排行榜商品的id
                    int next = Integer.parseInt(iterator.next());
                    name=shopBiz.queryShopName(next);
                    System.out.println(name+"-----");
                    if(i==1){
                        request.getSession().setAttribute("o",name);
                    }else if(i==2){
                        request.getSession().setAttribute("t",name);
                    }/*else if(i==3){
                        request.getSession().setAttribute("th",name);
                    }*/
                    System.out.println("i="+i);
                    name="";
                    i++;
                }
                //显示客户信息
                request.getSession().setAttribute("username",username);
                request.getSession().setAttribute("userid",user.getUserid());
                return "shop";
            }
            //密码用户名正确但超过限制次数了
            else {
                return "logno";
            }
        } else {
            //登陆失败
            Integer newCount = countUtils.IncrFailLoginCount(key, count);
            if (newCount >= 3) {
                return "logno";
            } else {
                return "index";
            }
        }
    }

    //注册
    @PostMapping("/goreg")
    public String registerU(HttpServletRequest request) {
        String username = null;
        String password = null;
        UserPo userPo = new UserPo();
        if (request.getParameter("username") != null) {
            username = request.getParameter("username");
            System.out.println(username + "-----------");
        }
        if (request.getParameter("password") != null) {
            password = request.getParameter("password");
            System.out.println(password + "----------");
        }
        userPo.setUsername(username);
        userPo.setPassword(password);
        //注册
        int n = userBiz.registerUser(userPo);
        System.out.println(n + "?????????");
        if (n != 0) {
            return "regok";
        } else {
            return "regno";
        }
    }

    //秒杀 并存值
    @PostMapping("/spikeshop")
    public String spikeShop(HttpServletRequest request, HttpSession session) {

        int shopId = Integer.parseInt(request.getParameter("shopId"));
        //查询商品 返回实体
        ShopEntity shopEntity = shopBiz.shopNum(shopId);
        //获取商品名、商品数量
        String shopName = shopEntity.getShopName();
        double shopNumber = shopEntity.getShopNumber();

        //查看redis数据库有无存储商品信息 zadd goodsList[key] shopNumber[score] shopId[value]
        String goodsList = "goodsList";
        double nowNum = -1;
        //通过排名来判断有无
        Long n = jedis.zrank(goodsList, String.valueOf(shopId));
        if (n == null) {
            //此时不存在
            //添加进去
            jedis.zadd(goodsList, shopNumber, String.valueOf(shopId));
        }
        Long a = jedis.zrank(goodsList, String.valueOf(shopId));
        if (a >= 0) {
            //此时存在
            System.out.println(jedis.zscore(goodsList, String.valueOf(shopId)));
            System.out.println("---------");
            nowNum = jedis.zscore(goodsList, String.valueOf(shopId));
            System.out.println(nowNum);
        }
        //秒杀
        if (shopNumber >0) {
            //此时秒杀成功 redis库存-1
            jedis.zincrby(goodsList, -1, String.valueOf(shopId));
            //如果 库存数量为0了 设置过期时间为1s
            /*if (jedis.zscore(goodsList, String.valueOf(shopId)) == 0) {
                jedis.expire(goodsList, 1);
            }*/
            //同步更新数据库信息 ->数量-1
            shopBiz.updateNumber(shopId);
            //--------抢购用户信息-------------
            //添加userId userName 到spikeList[key]  userid[score] username[value]
            String userName = (String) session.getAttribute("username");
            int userId = (int) session.getAttribute("userid");
            jedis.zadd("spikeList", userId, userName);
            //-----------销售排行榜------------
            //添加 商品shopnumber shopId 到shopList shopnumber[score] shopId[value]
            double shopnumber = -1;
            String shopList = "shopList";
            Long c = jedis.zrank(shopList, String.valueOf(shopId));
            if(c==null){
                //不存在
                jedis.zadd(shopList, shopnumber, String.valueOf(shopId));
                jedis.zincrby(shopList, 1, String.valueOf(shopId));
            }
            Long b = jedis.zrank(shopList, String.valueOf(shopId));
            if (b >= 0) {
                //存在
                // 排行里销量+1
                jedis.zincrby(shopList, 1, String.valueOf(shopId));
                System.out.println(jedis.zscore(shopList, String.valueOf(shopId)));
            }

            //同步添加到数据库
            int i = shopBiz.insertSpike(shopId, userId, userName);
            System.out.println("i=" + i);
            return "spikeok";
        } else
            return "spikeno";
    }

    //搜索
    @PostMapping("/seekgoods")
    public String seek(HttpServletRequest request, HttpSession session){
        String shopName=request.getParameter("shopName");
        System.out.println(shopName);
        ShopEntity shopEntity=shopBiz.seek(shopName);
        if(shopEntity!=null){
            return shopName;
        }else
            return "notfound";

    }
}
